package com.woniu.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

/**
 * @Classname MyConfig
 * @Description TODO
 * @Date 2025/8/8 16:24
 * @Created by pc
 */
@Configuration  // 表示当前类是一个配置类 相当于以前在spring框架中的 xml配置文件
// WebMvcConfigurer 接口是springboot的一个配置接口
public class MyConfig implements WebMvcConfigurer {

    /* 全局处理跨域*/
    // @Override
    // public void addCorsMappings(CorsRegistry registry) {
    //     // 针对的映射
    //     registry.addMapping("/**")
    //             .allowedOrigins("*")
    //             .allowedMethods("*")
    //             .allowedHeaders("*")
    //             .maxAge(3600);
    // }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        registrationBean.setFilter(new CorsFilter(source));
        registrationBean.setOrder(-1);
        return registrationBean;
    }



}
